/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 16:47:21
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-08-27 22:35:41
 */

import { familyList, familyPage, familyAddOrEdit, familyDelete } from 'services/family';

export default {
  namespace: 'familyList',
  state: {
    data: {
      list: [],
      pagination: {},
    },
    familyList: [],
  },

  effects: {
    *fetch({ payload, callback }, { call, put }) {
      const response = yield call(familyPage, payload);
      yield put({
        type: 'saveList',
        payload: response,
      });
    },

    *familyList({ payload, callback }, { call, put }) {
      const response = yield call(familyList, payload);
      yield put({
        type: 'saveFamilyList',
        payload: response,
      });
    },

    *familyAddOrEdit({ payload, callback }, { call, put }) {
      const response = yield call(familyAddOrEdit, payload);
      callback(response);
    },

    *familyDelete({ payload, callback }, { call, put }) {
      const response = yield call(familyDelete, payload);
      callback(response);
    },
  },

  reducers: {
    saveList(state, action) {
      const {
        data: { familyList, pageIndex, pageSize, recordCount },
      } = action.payload;

      const newList = familyList.map(v => {
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        data: {
          list: newList,
          pagination: {
            current: pageIndex,
            total: recordCount,
            pageSize,
          },
        },
      };
    },

    saveFamilyList(state, action) {
      const { data } = action.payload;

      if (!(data instanceof Array)) {
        return {
          ...state,
        };
      }
      const newList = data.map(v => {
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        familyList: newList,
      };
    },
  },
};
